import os
from http.server import SimpleHTTPRequestHandler, HTTPServer
import json
from .api.handlers import api_routes
from urllib.parse import urlparse, parse_qs

class CustomHTTPRequestHandler(SimpleHTTPRequestHandler):
    
    def do_GET(self):
        if self.path.startswith('/api/'):
            self.handle_api_request(False)
        else:
            # 获取静态文件
            self.serve_static_file()

    def do_POST(self):
        if self.path.startswith('/api/'):
            self.handle_api_request(True)
        else:
            self.send_error(404, "File Not Found")
    
    def handle_api_request(self,is_post:bool):
        handler = None
        for url, cur_handler in api_routes.items():
            if str(self.path).startswith(url):
                handler = cur_handler
                break

        if handler:
            if is_post:
                content_length = int(self.headers.get('Content-Length', 0))
                post_data = self.rfile.read(content_length) if content_length > 0 else b'{}'
                data = json.loads(post_data)
            else:
                parsed_path = urlparse(self.path)
                data = parse_qs(parsed_path.query)

            # 调用处理函数并获取响应数据
            response_data = handler(data)

            # 返回响应
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(response_data).encode())
        else:
            self.send_error(404, "API Not Found")

        # # 查找对应的处理函数
        # handler = None
        # for url,cur_handler in api_routes.items():
        #     if str(self.path).startswith(url):
        #         handler = cur_handler
        #         break
        # print(f"self.path = {self.path}")
        
        # if handler:
        #     print(self.headers["Content-Length"])

        #     if is_post:
        #         content_length = int(self.headers['Content-Length'])
        #         print(content_length)
        #         post_data = self.rfile.read(content_length)
        #         data = json.loads(post_data)
            
        #     # 调用处理函数并获取响应数据
        #     response_data = handler(data)
            
        #     # 返回响应
        #     self.send_response(200)
        #     self.send_header('Content-type', 'application/json')
        #     self.end_headers()
        #     self.wfile.write(json.dumps(response_data).encode())
        # else:
        #     self.send_error(404, "API Not Found")
    
    def serve_static_file(self):
        # 重写translate_path方法，使得静态文件从src目录下查找
        self.path = f"/static{self.path}"
        if os.path.isdir(self.path):
            self.path = os.path.join(self.path, "index.html")
        
        return super().do_GET()


def RunViewServer(server_class=HTTPServer, handler_class=CustomHTTPRequestHandler, port=8000):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print(f'Starting httpd on port {port}...')
    httpd.serve_forever()

# if __name__ == "__main__":
#     RunViewServer()

